package com.mac.hosp_pre.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.sys.entity.SysUser;
import com.mac.hosp_pre.sys.mapper.SysUserMapper;
import com.mac.hosp_pre.sys.model.LoginBody;
import com.mac.hosp_pre.sys.model.LoginUser;
import com.mac.hosp_pre.sys.security.context.AuthenticationContextHolder;
import com.mac.hosp_pre.sys.service.SysUserService;
import com.mac.hosp_pre.sys.util.TokenUtil;
import com.mac.hosp_pre.util.servlet.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private TokenUtil tokenService;

    @Override
    public LoginUser login(LoginBody loginUser) {
        try {
            if (StringUtils.isBlank(loginUser.getCode())) {
                throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"验证码不能为空");
            }
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser.getUsername(), loginUser.getPassword());
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            Authentication authentication = authenticationManager.authenticate(authenticationToken);
            LoginUser user = (LoginUser) authentication.getPrincipal();
            // 生成token
            String token = tokenService.createToken(user);
            user.setToken(token);
            tokenService.setLoginUser(user);
            return user;
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"用户名或密码错误");
            } else {
                throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
    }

    @Override
    public LoginUser getInfo() {
        return tokenService.getLoginUser(ServletUtils.getRequest());
    }

}
